package com.kurancy.web.controller;

import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kurancy.domain.KurancyUser;
import com.kurancy.domain.enums.State;
import com.kurancy.web.authentication.SessionManager;
import com.kurancy.web.authentication.service.AuthService;
import com.kurancy.web.controller.form.RegistrationForm;
import com.kurancy.web.util.DropdownUtil;

@Controller
public class RegistrationController {
	
	@Autowired 
	private AuthService authService;
	
	@Autowired
	private SessionManager sessionManager;

	@RequestMapping("/prepareregistration")
	public String registrationStep1(	ModelMap map, 
										Model uiModel, 
										HttpServletRequest req) {
		
		RegistrationForm form = new RegistrationForm();
		KurancyUser user = sessionManager.getKurancyUser(req);
		form.setKurancyUser(user);
		uiModel.addAttribute("registrationForm", form);
		uiModel.addAttribute("states", DropdownUtil.createNameValuePairsFromEnum(State.values(), "getName", "getStateAbbreviation", true));
		return "registration/step1";
	}
	
	@RequestMapping("/registration/complete")
	public String completeRegistration(	@Valid RegistrationForm form,
										BindingResult bindingResult,
										ModelMap map, 
										Model uiModel, 
										HttpServletRequest req) {
		
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute("registrationForm", form);
			uiModel.addAttribute("states", DropdownUtil.createNameValuePairsFromEnum(State.values(), "getName", "getStateAbbreviation", true));
			return "registration/step1";
		}
		Date now = new Date(System.currentTimeMillis());
		KurancyUser preRegistrationUser = sessionManager.getKurancyUser(req);
		preRegistrationUser.setCity(form.getKurancyUser().getCity());
		preRegistrationUser.setStateAbbr(form.getKurancyUser().getStateAbbr());
		preRegistrationUser.setCreatedOn(now);
		preRegistrationUser.setIsActive(true);
		preRegistrationUser.setModifiedOn(now);
		preRegistrationUser.setPaypalCredential(form.getKurancyUser().getPaypalCredential());
		preRegistrationUser.persist();
		
		authService.cacheFacebookAuthentication(preRegistrationUser, req);
		
		return "registration/complete";
	}
}
